'use client'

import { useState, useEffect } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { Search, X, Filter } from 'lucide-react'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'

interface Category {
  id: string
  name: string
  icon: string
}

interface SearchBarProps {
  categories?: Category[]
}

export function SearchBar({ categories = [] }: SearchBarProps) {
  const router = useRouter()
  const searchParams = useSearchParams()
  const [query, setQuery] = useState(searchParams.get('q') || '')
  const [selectedCategory, setSelectedCategory] = useState(searchParams.get('category') || '')
  const [showFilters, setShowFilters] = useState(false)

  // 实时搜索，但添加防抖
  useEffect(() => {
    const timer = setTimeout(() => {
      updateURL()
    }, 300)

    return () => clearTimeout(timer)
  }, [query, selectedCategory])

  const updateURL = () => {
    const params = new URLSearchParams(searchParams)

    if (query.trim()) {
      params.set('q', query.trim())
    } else {
      params.delete('q')
    }

    if (selectedCategory) {
      params.set('category', selectedCategory)
    } else {
      params.delete('category')
    }

    router.push(`/?${params.toString()}`)
  }

  const handleCategorySelect = (categoryId: string) => {
    setSelectedCategory(categoryId === selectedCategory ? '' : categoryId)
  }

  const clearSearch = () => {
    setQuery('')
    setSelectedCategory('')
    router.push('/')
  }

  const hasActiveFilters = query || selectedCategory

  return (
    <div className="w-full max-w-4xl mx-auto space-y-4">
      {/* 主搜索框 */}
      <div className="relative">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
          <Input
            type="text"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="搜索工具名称、描述..."
            className="pl-10 pr-16 sm:pr-20 h-12 text-base"
          />
          <div className="absolute right-2 top-1/2 transform -translate-y-1/2 flex items-center gap-1 sm:gap-2">
            {hasActiveFilters && (
              <Button
                variant="ghost"
                size="sm"
                onClick={clearSearch}
                className="h-8 w-8 p-0"
                title="清除搜索"
              >
                <X className="h-3 w-3 sm:h-4 sm:w-4" />
              </Button>
            )}
            {categories.length > 0 && (
              <Button
                variant="outline"
                size="sm"
                onClick={() => setShowFilters(!showFilters)}
                className={`h-8 ${showFilters ? 'bg-blue-50 border-blue-200' : ''}`}
                title="筛选"
              >
                <Filter className="h-3 w-3 sm:h-4 sm:w-4" />
              </Button>
            )}
          </div>
        </div>
      </div>

      {/* 分类筛选 */}
      {showFilters && categories.length > 0 && (
        <div className="bg-white border border-gray-200 rounded-lg p-3 sm:p-4 shadow-sm">
          <div className="flex items-center gap-2 mb-3">
            <Filter className="h-4 w-4 text-gray-500" />
            <span className="text-sm font-medium text-gray-700">按分类筛选</span>
          </div>
          <div className="flex flex-wrap gap-1.5 sm:gap-2">
            <Button
              variant={!selectedCategory ? "default" : "outline"}
              size="sm"
              onClick={() => setSelectedCategory('')}
              className="h-8 text-xs sm:text-sm"
            >
              全部
            </Button>
            {categories.map((category) => (
              <Button
                key={category.id}
                variant={selectedCategory === category.id ? "default" : "outline"}
                size="sm"
                onClick={() => handleCategorySelect(category.id)}
                className="h-8 text-xs sm:text-sm"
              >
                <span className="mr-1 text-sm">{category.icon}</span>
                <span className="hidden sm:inline">{category.name}</span>
                <span className="sm:hidden">{category.name.slice(0, 2)}</span>
              </Button>
            ))}
          </div>
        </div>
      )}

      {/* 搜索状态提示 */}
      {hasActiveFilters && (
        <div className="flex items-center gap-2 text-sm text-gray-600">
          <span>当前筛选:</span>
          {query && (
            <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
              搜索: "{query}"
            </span>
          )}
          {selectedCategory && (
            <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
              分类: {categories.find(c => c.id === selectedCategory)?.name}
            </span>
          )}
          <Button
            variant="ghost"
            size="sm"
            onClick={clearSearch}
            className="h-6 px-2 text-xs"
          >
            清除筛选
          </Button>
        </div>
      )}
    </div>
  )
}
